﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DynaPrecision.CommonCollection
{
	public class IndexerTranslator<T> : IList<T>
	{
		public IList<T> UnderlyingList { get; set; }
		public Func<int, int> IndexTranslateFunction { get; set; }
		public Func<int, int> ReverseTranslateFunction { get; set; }
		#region IList<T> Members

		public int IndexOf(T item)
		{
			return ReverseTranslateFunction(UnderlyingList.IndexOf(item));
		}

		public void Insert(int index, T item)
		{
			throw new NotSupportedException("Wrapped List not supporting this because we cannot find the position");
		}

		public void RemoveAt(int index)
		{
			throw new NotSupportedException("Wrapped List not supporting this because we cannot find the position");
		}

		public T this[int index]
		{
			get
			{
				return UnderlyingList[IndexTranslateFunction(index)];
			}
			set
			{
				UnderlyingList[IndexTranslateFunction(index)] = value;
			}
		}

		#endregion

		#region ICollection<T> Members

		public void Add(T item)
		{
			throw new NotSupportedException("Wrapped List not supporting this because we cannot find the position");
		}

		public void Clear()
		{
			throw new NotSupportedException("Wrapped List not supporting this because we cannot find the position");
		}

		public bool Contains(T item)
		{
			throw new NotSupportedException("Wrapped List not supporting this because we cannot find the position");
		}

		public void CopyTo(T[] array, int arrayIndex)
		{
			throw new NotSupportedException("Wrapped List not supporting this because we cannot find the position");
		}
		private int _count;
		public int Count
		{
			get
			{
				if (_count == 0)
				{
					return this.UnderlyingList.Count;
				}
				else
				{
					return _count;
				}
			}
			set
			{
				_count = value;
			}
		}

		public bool IsReadOnly
		{
			get { return true; }
		}

		public bool Remove(T item)
		{
			throw new NotSupportedException("Wrapped List not supporting this because we cannot find the position");
		}

		#endregion

		#region IEnumerable<T> Members

		public IEnumerator<T> GetEnumerator()
		{
			for (int i = 0; i < this.Count; i++)
			{
				yield return this[i];
			}
		}

		#endregion

		#region IEnumerable Members

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return (this as IEnumerable<T>).GetEnumerator();
		}

		#endregion
	}
}
